<template>
  <div class="container">
    <div class="table-data">
      <el-card class="box-card">
        <el-row style="margin-bottom:20px;">
          <!-- 刷新 -->
          <el-button
            type="success"
            icon="el-icon-plus"
            size="small"
            @click="addClassify"
            >添加分类</el-button
          >
        </el-row>

        <el-table :data="dataShow" stripe border style="width: 100%">
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="type_name" label="商品名称"></el-table-column>
          <el-table-column prop="parent_id" label="分类等级">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.parent_id == '0'">一级</el-tag>
              <el-tag type="success" v-if="scope.row.parent_id != '0'"
                >二级</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="创建时间"
            :formatter="formatter"
          ></el-table-column>
          <el-table-column
            prop="update_time"
            label="更新时间"
            :formatter="formatter"
          ></el-table-column>
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="editGoods(scope.row)"
                >修改</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteGoods(scope.row.good_type_id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- <tree-table :data="catelist" :columns="columns"></tree-table> -->

        <!-- 分页 -->
        <!-- <el-pagination
            style="margin-top:20px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination> -->

        <!-- 添加分类 -->
        <el-dialog
          title="添加分类"
          :append-to-body="true"
          :visible.sync="addCateDialogVisible"
          width="50%"
          @close="addCateDialogClosed"
        >
          <!-- 添加分类的表单 -->
          <el-form
            :model="addCateForm"
            :rules="addCateFormRules"
            ref="addCateFormRef"
            label-width="100px"
          >
            <el-form-item label="分类名称：" prop="name">
              <el-input v-model="addCateForm.name"></el-input>
            </el-form-item>
           
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCate">确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
          title="修改分类"
          :append-to-body="true"
          :visible.sync="editDialogVisible"
          width="50%"
          @close="editDialogClosed"
        >
          <!-- 添加分类的表单 -->
          <el-form
            :model="editForm"
            :rules="editFormRules"
            ref="editFormRef"
            label-width="100px"
          >
            <el-form-item label="分类名称：" prop="type_name">
              <el-input v-model="editForm.type_name"></el-input>
            </el-form-item>
            <el-form-item label="当前id：" prop="good_type_id" type="number">
              <el-input v-model="editForm.good_type_id" disabled></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editCate">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataShow: [],
      token: window.sessionStorage.getItem("token"),
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      addCateForm: {
        token: window.sessionStorage.getItem("token"),
        name: "",
        pid: 1
      },
      addCateFormRules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }]
        // pid: [{ required: true, validator: validatepid, trigger: "blur" }]
      },

      //修改会话框状态值
      editDialogVisible: false,
      editFormRules: {
        type_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
        // parent_id: [
        //   { required: true, message: "请输入父级id", trigger: "blur" }
        // ]
      },
      editForm: {
        type_name: "",
        parent_id: 1,
        good_type_id: null
      }
    };
  },
  created() {
    this.getShowList();
  },
  methods: {
    //获取分类信息
    async getShowList() {
      const { data: res } = await this.$http.post("/api/admin/goodsTypeList", {
        token: this.token
      });
      console.log(res);
      this.dataShow = res.data;
    },
    //处理时间戳
    formatter(row, column, cellValue, index) {
      if (cellValue == null || cellValue == "") return "";
      let date = new Date(parseInt(cellValue) * 1000);
      let Y = date.getFullYear() + "-";
      let M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1) + "-"
          : date.getMonth() + 1 + "-";
      let D =
        date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
      let h =
        date.getHours() < 10
          ? "0" + date.getHours() + ":"
          : date.getHours() + ":";
      let m =
        date.getMinutes() < 10
          ? "0" + date.getMinutes() + ":"
          : date.getMinutes() + ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D;
    },
    //打开会话框状态
    addClassify() {
      this.addCateDialogVisible = true;
    },
    // 监听对话框的关闭事件，重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
    },
    //添加
    async addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return;
        console.log(this.addCateForm);
        for(let i = 0 ; i < this.dataShow.length; i++){
          if(this.dataShow[i].type_name == this.addCateForm.name){
            this.$message.info('分类名已存在');
            return;
          }
        }
        
        const { data: res } = await this.$http.post(
          "/api/admin/addGoodType",
          this.addCateForm
        );
        console.log(res);
        if (res.code != 2000) return this.$message.error("添加失败！");
        this.$message.success("添加成功！");
        this.addCateDialogVisible = false;
        this.getShowList();
      });
    },
    handleSizeChange() {},
    handleCurrentChange() {},

    //删除
    async deleteGoods(id) {
      // console.log(id)
      const confirmRes = await this.$confirm(
        "此操作将永久删除该条分类信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (confirmRes !== "confirm") {
        return this.$message.info("已取消删除！");
      }
      const { data: res } = await this.$http.post("/api/admin/deleteGoodtype", {
        token: this.token,
        id
      });
      console.log(res);
      this.getShowList();
    },
    //修改
    editGoods(data) {
      this.editDialogVisible = true;
      this.editForm = data;
      console.log(this.editForm);
    },
    // 监听对话框的关闭事件，重置表单数据
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //确定修改
    async editCate() {
      console.log(this.editForm);
      let tmp = {};
      tmp.token = window.sessionStorage.getItem("token");
      tmp.name = this.editForm.type_name;
      tmp.pid = Number(this.editForm.parent_id);
      tmp.id = this.editForm.good_type_id;
      const { data: res } = await this.$http.post(
        "/api/admin/addGoodType",
        tmp
      );
      // console.log(res)
      if (res.code !== 2000) return this.$message.error("修改失败！");
      this.editDialogVisible = false;
      this.$message.success("修改成功!");
      this.getShowList();
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.el-table__body-wrapper {
  font-size: 13px;
}
.container {
  min-height: 850px;
  background: #f6f6f6;
  padding-top: 20px;

  .table-data {
    padding: 0 20px;
  }

  .nav-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  /deep/.el-table td,
  /deep/.el-table th {
    text-align: center;
  }
  /deep/.el-form-item__label {
    width: 93px !important;
  }
  /deep/.el-input {
    width: 98%;
  }
}
</style>
